package log_utils

import (
	"fmt"
	"io"
	"os"
	"time"

	"github.com/natefinch/lumberjack"
	log "github.com/sirupsen/logrus"
)

func Init() {
	RotateLog()
	// 创建一个文件用于写日志
	file, err := os.Create("app.log")
	if err != nil {
		fmt.Printf("Error creating log file: %v\n", err)
		return
	}
	defer file.Close()

	// 开始写日志
	logger := lumberjack.Logger{
		Filename:   "app.log",
		MaxSize:    10, // MB
		MaxBackups: 5,
		MaxAge:     30, // 保留日志天数
		Compress:   true,
	}
	// 设置日志切分时间
	go func() {
		for {
			// 等待一个小时
			time.Sleep(1 * time.Hour)
			RotateLog()
		}
	}()

	log.SetOutput(&logger)
	log.SetFormatter(&log.TextFormatter{
		FullTimestamp: true,
	})
}

// 返回基于当前时间的日志文件名
func GetLogFilename() string {
	a := fmt.Sprintf("app_%s.log", time.Now().Format("2006-01-02_15"))
	return a
}

// 重新创建日志文件
func RotateLog() {
	newFilename := GetLogFilename()

	// 打开源文件
	sourceFile, err := os.Open("app.log")
	if err != nil {
		fmt.Printf("Error opening source file: %v\n", err)
		return
	}
	defer sourceFile.Close()

	// 创建目标文件
	destinationFile, err := os.Create(newFilename)
	if err != nil {
		fmt.Printf("Error creating destination file: %v\n", err)
		return
	}
	defer destinationFile.Close()

	// 复制文件内容
	bytesCopied, err := io.Copy(destinationFile, sourceFile)
	if err != nil {
		fmt.Printf("Error copying file: %v\n", err)
		return
	}
	fmt.Printf("Copied %d bytes from app.log to %s\n", bytesCopied, newFilename)

	// 截断文件为 0 字节，清空内容
	err1 := os.Truncate("app.log", 0)
	if err1 != nil {
		fmt.Printf("Error truncating file: %v\n", err1)
		return
	}

	fmt.Println("app.log content has been cleared.")
}
